/**
 * 先实现es5
 */

const obj = {
    a: 1,
    b: 2,
    c: 3
}

const obj2 = {
    a: 1,
    b: 3
}

Object.prototype._definePorperty_ = function () {
    const self = this
    const tempObj = JSON.parse(JSON.stringify(self))
    for (var i in tempObj) {
        tempObj[`_${i}`] = tempObj[i]
    }
    for (let i in self) {
        self.hasOwnProperty(i) ? Object.defineProperty(self, i, {
            get: function () {
                console.log(`${i} = ${self[`_${i}`] || tempObj[`_${i}`]}`)
                return self[`_${i}`] || tempObj[`_${i}`]
            },
            set: function (value) {
                self[`_${i}`] = value
            }
        }) : ''
    }
}

obj._definePorperty_()
obj.a = 2
console.log(obj.a)
console.log(obj.a + 3)

console.log(`=========================分割线====================`)

/**
 * proxy 
 */

const onWatch = (obj, setData, getData) => {
    let handler = {
        get(target, property, receiver) {
            return getData(target, property, receiver)
        },
        set(target, property, value, receiver) {
            return setData(target, property, value)
        }
    }
    return new Proxy(obj, handler)
}

const p = onWatch(obj2,
    (target, property, value) => {
        console.log('WRITING')
        return Reflect.set(target, property, value)
    },
    (target, property, receiver) => {
        console.log('LOADING')
        return Reflect.get(target, property, receiver)
    }
)

p.a = 3
console.log(p.a)